// BookDetails.js
import React, { useState, useEffect } from 'react';
import { Modal, Button, Input, Space, Upload, Rate, Typography } from 'antd';
import { EditOutlined, SaveOutlined, UploadOutlined } from '@ant-design/icons';

const { Title } = Typography;
const defaultImage = 'https://via.placeholder.com/150'; // 默认图片

const BookDetails = ({ visible, onClose, book }) => {
  const [editing, setEditing] = useState(false);
  const [image, setImage] = useState(book?.image || defaultImage);
  const [reflection, setReflection] = useState(book?.reflection || '');
  const [rating, setRating] = useState(book?.rating || 0);

  useEffect(() => {
    setImage(book?.image || defaultImage);
    setReflection(book?.reflection || '');
    setRating(book?.rating || 0);
  }, [book]);
  const handleImageChange = async file => {
    console.log('New image file:', file);

    const formData = new FormData();
    formData.append('file', file);
    formData.append('bookId', book?.id);

    try {
      const response = await fetch('http://localhost:29157/api/book/image', {
        method: 'POST',
        body: formData,
      });

      if (response.ok) {
        const data = await response.json();
        console.log(data);
        if (data.status) {
          setImage(data.data.imageUrl); // 更新图像 URL
        } else {
          // 处理 API 返回的错误消息
          console.error(data.data.message);
        }
      } else {
        console.error('Error uploading image:', response.statusText);
      }
    } catch (error) {
      console.error('Error uploading image:', error);
    }
  };

  const handleSave = async () => {
    // TODO: 将更改保存到后端
    console.log('Save changes');

    try {
      const response = await fetch('http://localhost:29157/api/book/detail', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          id: book?.id,
          reflection: reflection,
          rating: rating,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        if (data.success) {
          console.log('Successfully saved changes');
        } else {
          // 处理 API 返回的错误消息
          console.error(data.message);
        }
      } else {
        console.error('Error saving changes:', response.statusText);
      }
    } catch (error) {
      console.error('Error saving changes:', error);
    }

    setEditing(false);
  };

  return (
    <Modal
      visible={visible}
      onCancel={onClose}
      title={book?.title}
      footer={null}
      width={800}>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <div style={{ width: '50%', textAlign: 'center' }}>
          <img
            src={image}
            alt='Book cover'
            style={{ width: '80%', maxHeight: '300px' }}
          />
          {editing && (
            <Upload
              accept='image/*'
              showUploadList={false}
              beforeUpload={handleImageChange}>
              <Button icon={<UploadOutlined />}>更换插图</Button>
            </Upload>
          )}
          <Title
            level={4}
            style={{ marginTop: '16px' }}>
            {book?.title}
          </Title>
          {editing ? (
            <Rate
              value={rating}
              onChange={value => setRating(value)}
              allowHalf={true}
            />
          ) : (
            <Rate
              value={rating}
              disabled
              allowHalf={true}
            />
          )}
        </div>
        <div style={{ width: '50%' }}>
          {!editing ? (
            <p>{reflection || '暂无读后感'}</p>
          ) : (
            <Input.TextArea
              value={reflection}
              onChange={e => setReflection(e.target.value)}
              style={{ width: '100%', marginBottom: '10px' }}
              rows={10} // 设置文本框的行数
            />
          )}
        </div>
      </div>
      <Space style={{ marginTop: '20px' }}>
        {editing ? (
          <Button
            icon={<SaveOutlined />}
            type='primary'
            onClick={handleSave}>
            保存
          </Button>
        ) : (
          <Button
            icon={<EditOutlined />}
            type='primary'
            onClick={() => setEditing(true)}>
            编辑
          </Button>
        )}
      </Space>
    </Modal>
  );
};

export default BookDetails;
